package com.qianyu.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianyu.project.core.context.user.FlowUserManager;
import com.qianyu.project.entity.*;
import com.qianyu.project.mapper.SystemUserMapper;
import com.qianyu.project.service.ISystemRoleService;
import com.qianyu.project.service.ISystemUserRoleService;
import com.qianyu.project.service.ISystemUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gs
 * @date create in 2020/12/24 8:08
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper,SystemUser> implements ISystemUserService, UserDetailsService {

    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private ISystemRoleService systemRoleService;
    @Autowired
    private ISystemUserRoleService systemUserRoleService;
    @Autowired
    private FlowUserManager flowUserManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        SystemUser systemUser = systemUserMapper.selectOne(
                new QueryWrapper<SystemUser>()
                        .eq("user_status", "Y")
                        .eq("user_name", username)
        );
        //判断是否为空
        if (systemUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //封装权限
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //查询角色
        List<SystemRole> systemRoles = systemRoleService.getByUser(systemUser.getId());
        List<Integer> userRoles = Lists.newArrayList();
        //封装角色权限
        systemRoles.iterator().forEachRemaining(systemRole -> {
            StringBuilder builder = new StringBuilder("ROLE_");
            builder.append(systemRole.getRoleName());
            grantedAuthorities.add(new SimpleGrantedAuthority(builder.toString()));
            userRoles.add(systemRole.getId());
        });
        //存放角色信息用于审批模块
        String roles = StringUtils.collectionToCommaDelimitedString(userRoles);
        systemUser.setUserRoles(roles);
        //设置权限到用户对象中
        systemUser.setGrantedAuthorities(grantedAuthorities);
        //返回
        return systemUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePassword(SystemUser systemUser) {
        //密码加密
        systemUser.setUserPwd(new BCryptPasswordEncoder().encode(systemUser.getUserPwd()));
        //设置用户id
        systemUser.setId(flowUserManager.getFlowUser().getId());
        //修改用户
        systemUserMapper.updateById(systemUser);
        //修改用户角色
        SystemUserRole systemUserRole = new SystemUserRole();
        systemUserRole.setSystemUserId(systemUser.getId());
        systemUserRole.setSystemRoleId(3);
        systemUserRoleService.update(
                systemUserRole,
                new UpdateWrapper<SystemUserRole>()
                        .eq("system_user_id", systemUser.getId())
        );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(SystemUser systemUser) {
        //截取密码
        String password = systemUser.getUserPhone().substring(7);
        //密码加密
        systemUser.setUserPwd(new BCryptPasswordEncoder().encode(password));
        //保存
        systemUserMapper.insert(systemUser);
        //分配为初建竞标公司角色
        SystemUserRole systemUserRole = new SystemUserRole();
        systemUserRole.setSystemUserId(systemUser.getId());
        systemUserRole.setSystemRoleId(49);
        systemUserRoleService.save(systemUserRole);
    }
}